package com.heima.user.filter;

import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @作者 itcast
 * @创建日期 2021/4/20 9:54
 **/
@Component
@WebFilter(value = "appTokenFilter",urlPatterns = "/*")
@Slf4j
public class AppTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 获取请求对象
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        // 2. 获取请求头中的 userId
        String userId = request.getHeader("userId");
        log.info("user微服务   登录用户检查 ==> userId: {}",userId);
        // 3. 如果有 且不等于0: 封装ApUser 存入到 ThreadLocal中
        if(StringUtils.isNotBlank(userId)&&Integer.valueOf(userId)!=0){
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            AppThreadLocalUtils.setUser(apUser);
        }
        // 4. 放行请求
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
